package com.jeeplus.modules.cms.statistic.web;

import com.jeeplus.cms.support.TreeBuilder;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.cms.column.entity.CmsColumn;
import com.jeeplus.modules.cms.statistic.service.StatisticService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Sawyer
 * @date 2020-11-25
 */
@RestController
@RequestMapping(value = "/cms/statistic")
public class StatisticController {

    @Autowired
    private StatisticService statisticService;

    /**
     * 统计栏目点击量
     */
    @RequiresPermissions("cms:statistic:hit:list")
    @GetMapping("/columnhit")
    public AjaxJson columnHit(CmsColumn cmsColumn) {
        List<CmsColumn> tree = TreeBuilder.buildTree(statisticService.hitsStats(cmsColumn), null, null);
        summaryInfo(tree);
        return AjaxJson.success().put("treeData", tree);
    }

    /**
     * 遍历合并统计信息,父节点的点击量=子节点点击量之和
     */
    private void summaryInfo(List<CmsColumn> list) {
        for (CmsColumn column : list) {
            if (null != column.getChildren() && column.getChildren().size() > 0) {
                column.setHits(0);
                column.setInfoCount(0);
                column.setDetailsHits(0);
                column.getChildren().forEach(c -> {
                    if (null != c.getChildren()) {
                        summaryInfo(c.getChildren());
                    }
                    column.setHits(column.getHits() + (null == c.getHits() ? 0 : c.getHits()));
                    column.setInfoCount(column.getInfoCount() + (null == c.getInfoCount() ? 0 : c.getInfoCount()));
                    column.setDetailsHits(column.getDetailsHits() + (null == c.getDetailsHits() ? 0 : c.getDetailsHits()));

                });
            } else {
                column.setHits(null == column.getHits() ? 0 : column.getHits());
                column.setInfoCount(null == column.getInfoCount() ? 0 : column.getInfoCount());
                column.setDetailsHits(null == column.getDetailsHits() ? 0 : column.getDetailsHits());
            }
        }
    }
}
